<?php
/**
* Authentication Controller
*/
class Auth extends Controller
{
  
  function Auth()
  {
    parent::Controller();
  }
  
  function index() {
    redirect('auth/login');
  }
  
  function login() {
    if($this->authentication->logged_in()) {
      redirect();
    }
    
    /* Para referers de GET */
    if($this->input->get('referer')) {
      $this->session->set_userdata('login_referer', urldecode($this->input->get('referer')));
    }
    
    $this->load->library('form_validation');
    
    /* Titulo */
    $this->layouts->set_title('Ingresar');
    $this->layouts->add_js('js/auth');
    
    /* Recordamos el email */
    $this->load->helper('cookie');
    $email = get_cookie('sgramos_email');
    
    $this->form_validation->set_rules(array(
      array(
        'field' => 'email',
        'label' => 'email',
        'rules' => 'valid_email|required'
      ),
      array(
        'field' => 'password',
        'label' => 'contrase&ntilde;a',
        'rules' => 'required'
      )
    ));
    
    /* Referer */
    $data = array('referer' => 'null', 'email' => $email);
    if($referer = $this->session->userdata('login_referer')) {
      $data['referer'] = $referer;
    }
    
    $referer = $referer != '' ? $referer : 'null';
    
    if($this->form_validation->run() === FALSE) {
      $this->layouts->view('auth/login', $data);
    }
    else {
      /* Recordamos el email */
      set_cookie(array(
        'name' => 'sgramos_email',
        'value' => $this->input->post('email'),
        'expire' => 60*60*24*7 /* Una semana */
      ));
      
      if($this->authentication->login(
        $this->input->post('email'), 
        $this->input->post('password'),
        array('active' => 't')
      )) {
        /* Ingreso Exitoso */
        $this->session->unset_userdata('login_referer');
        
        if($referer != 'null') {
          redirect($referer);
        }
        else {
          redirect('mysubjects');
        }
      }
      else {
        /* Fail */
        $data['error'] = true;
        $data['email'] = $email;
        $this->layouts->view('auth/login', $data);
      }
    }
  }
  
  function logout() {
    $this->authentication->logout();
    redirect('/');
  }
}
